<?php

namespace MMC\Statistics\BaiDu\Libs;


use MMC\Statistics\BaiDu\Config;

class LoginConnection extends AbstractClient
{
    public $url = '';

    public $headers;

    public $postData;

    public function init(Config $config, $url)
    {
        $this->url = $url;

        $this->headers = array('UUID: ' . $config->getUUID(), 'account_type: '. $config->getAccountType(), 'Content-Type: data/gzencode and rsa public encrypt;charset=UTF-8');
    }

    public function genPostData($data)
    {
        $index = 0;

        $jsonData = json_encode($data);

        $gzData   = gzencode($jsonData, 9);

        $rsa = new RsaPublicEncrypt();

        $encryptData = '';

        while ($index < strlen($gzData)) {
            $gzPackData = substr($gzData, $index, 117);
            $index +=117;
            $encryptData .= $rsa->pubEncrypt($gzPackData);
        }

        $this->postData = $encryptData;
    }

    public function parseResponse($response)
    {
        try {
            $return['code'] = ord($response[0])*64 + ord($response[1]);

            if ($return['code'] === 0) {
                $return['data'] = substr($response, 8);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return $return;
    }

}